<?php

namespace fast;


use Exception;


class Office2Pdf
{

    /**
     * office文件转pdf输出方法
     * @param $file_path
     * @return string
     */
    public function office2pdf($file_path, $filename): string
    {
        $jodconverter_path = "/opt/jodconverter-2.2.2/lib/jodconverter-cli-2.2.2.jar";
        $infile_path = "/www/wwwroot/project/lcj/wenzhang/public" . $file_path;
        $rand_path = $filename . '.pdf'; //定义随机生成一个pdf格式文件名
        $outfile_path = "/www/wwwroot/project/lcj/wenzhang/public/office2pdf/" . $rand_path;
        $this->word2pdf($infile_path, $outfile_path, $jodconverter_path);
        return "/office2pdf/" . $rand_path;
    }


    /**
     * word2pdf() 执行jodconverter用openOffice转pdf代码
     * @param $infile_path
     * @param $outfile_path
     * @param $jodconverter_path
     * @return bool
     */
    public function word2pdf($infile_path, $outfile_path, $jodconverter_path): bool
    {
        if (empty($infile_path)) return false;
        try {
            $set_charset = 'export LANG=en_US.UTF-8;'; //为防止中文文件转pdf时exec()函数执行出错 设置字符集为utf-8
            $p = "java -jar " . $jodconverter_path . ' ' . $infile_path . ' ' . $outfile_path;
            exec($set_charset . $p);
        } catch (Exception $e) {
            return false;
        }
        return true;
    }


    /**
     * 获取PDF文件页数的函数获取
     * 文件应当对当前用户可读
     * @param  [string] $path [文件路径]
     * @return int
     */
    public function getPdfPages($outfile_path): int
    {
        if (!file_exists($outfile_path)) return 0;
        if (!is_readable($outfile_path)) return 0;
        // 打开文件
        $fp = @fopen($outfile_path, "r");
        if (!$fp) {
            return 0;
        } else {
            $max = 0;
            while (!feof($fp)) {
                $line = fgets($fp, 255);
                if (preg_match('/\/Count [0-9]+/', $line, $matches)) {
                    preg_match('/[0-9]+/', $matches[0], $matches2);
                    if ($max < $matches2[0]) $max = $matches2[0];
                }
            }
            fclose($fp);
            // 返回页数
            return $max;
        }
    }


}

